package com.elong.qq.http;

import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * QQHttpCookieJar
  * @Title: QQHttpCookieJar
  * @Desription 
  * @author Guanguo.Gao
  * @date 2015年1月13日 上午9:08:31
 */
public class QQHttpCookieJar {
    
    /**
     * 日志
     */
    private static final Logger LOG = LoggerFactory.getLogger(QQHttpCookieJar.class);
    
    private List<QQHttpCookie> cookieContainer;
    
    public QQHttpCookieJar(){
	this.cookieContainer = new ArrayList<>();
    }

    
    public QQHttpCookie getCookie(String name){
	Iterator<QQHttpCookie> iter = cookieContainer.iterator();
	while(iter.hasNext()){
	    QQHttpCookie cookie = iter.next();
	    if(cookie.getName().equals(name)){
		return cookie;
	    }
	}
	return null;
    }
    
    public void updateCookies(List<String> tmpCookies){
	List<String> newCookies = new ArrayList<>();
	if(tmpCookies != null){
	    newCookies.addAll(tmpCookies);
	}
	
	if(newCookies.size() > 0){
	    Iterator<String> nit = newCookies.iterator();
	    while(nit.hasNext()){
		QQHttpCookie newCookie = new QQHttpCookie(nit.next());
		QQHttpCookie oldCookie = this.getCookie(nit.next());
		//如果有同名的，这删除以前的
		if(oldCookie != null){
		    cookieContainer.remove(oldCookie);
		    if(newCookie.getValue() != null && newCookie.getValue().length() > 0){
			cookieContainer.add(newCookie);
			LOG.debug("[Update Cookie] " + newCookie);
		    }
		}else{
		    cookieContainer.add(newCookie);
		    LOG.debug("[New Cookie] " + newCookie);
		}
	    }
	}
    }
    
    public String getCookieHeader(String url){
	URL u = null;
	try {
	    u = new URL(url);
	} catch (Exception e) {
	    throw new RuntimeException(e);
	}
	
	Iterator<QQHttpCookie> cit = cookieContainer.iterator();
	StringBuffer buffer = new StringBuffer();

	while(cit.hasNext()){
	    QQHttpCookie cookie = cit.next();
	    if(cookie.getExpireDate() != null && cookie.getExpireDate().before(new Date())){
		cit.remove();
		LOG.debug("[Remove cookie] " + cookie);
	    }else if(u.getPath().startsWith(cookie.getPath())){
		buffer.append(cookie.getName());
		buffer.append("=");
		buffer.append(cookie.getValue());
		buffer.append("; ");
	    }else{}
	}
	return buffer.toString();
    }
}
